package com.deliccio.util;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.deliccio.connect.DAO;
import com.deliccio.connect.Entidad;
import com.deliccio.entitys.Producto;

public class Util{
	
	private static Logger log = Logger.getLogger(Util.class);

	public static String generarCodigo(String entidad,String nombre){
		Random random=new Random();
		Calendar c=Calendar.getInstance();
		int anio=c.get(Calendar.YEAR);
		int mes=c.get(Calendar.MONTH);
		String strMes="";
		if(mes < 10){
			strMes="0" + String.valueOf(mes);
		}
		else
			strMes=String.valueOf(mes);
		int dia=c.get(Calendar.DAY_OF_MONTH);
		String strDia="";
		if(dia < 10){
			strDia="0" + String.valueOf(dia);
		}
		else
			strDia=String.valueOf(dia);
		// entidad.substring(0,4)
		String codigo=entidad.toLowerCase() + "_" + anio + "_" + strMes + "_" + strDia + "_" + random.nextInt(10000000) + "_" + nombre;
		return codigo;
	}

	public static List<String> desintegrarCodigo(String codigo){
		List<String> lst=new ArrayList<String>();
		String token="_",entidad,anio,mes,dia,ramdon,nombre;
		entidad=codigo.substring(0,codigo.indexOf(token));
		lst.add(entidad);
		codigo=codigo.substring(codigo.indexOf(token) + 1,codigo.length());
		anio=codigo.substring(0,codigo.indexOf(token));
		lst.add(anio);
		codigo=codigo.substring(codigo.indexOf(token) + 1,codigo.length());
		mes=codigo.substring(0,codigo.indexOf(token));
		lst.add(mes);
		codigo=codigo.substring(codigo.indexOf(token) + 1,codigo.length());
		dia=codigo.substring(0,codigo.indexOf(token));
		lst.add(dia);
		codigo=codigo.substring(codigo.indexOf(token) + 1,codigo.length());
		ramdon=codigo.substring(0,codigo.indexOf(token));
		lst.add(ramdon);
		codigo=codigo.substring(codigo.indexOf(token) + 1,codigo.length());
		nombre=codigo.substring(0,codigo.length());
		lst.add(nombre);
		return lst;
	}

	public static String ruta(List<String> lst){
		String ruta="/";
		for(int i=0;i < lst.size();i++){
			ruta+=lst.get(i);
			if(i < lst.size() - 1){
				ruta+="/";
			}
		}
		return ruta;
	}

	@SuppressWarnings("unchecked")
	public static String crearJson(Map<? extends Object,? extends Object> objeto){
		Set<Object> keys=(Set<Object>) objeto.keySet();
		StringBuffer sb=new StringBuffer("{");
		for(Object key : keys){
			if(sb.length() > 1){
				sb.append(",");
			}
			sb.append("\"" + key.toString() + "\"");
			sb.append(':');
			sb.append("\"" + objeto.get(key).toString() + "\"");
		}
		sb.append("}");
		return sb.toString();
	}

	@SuppressWarnings("deprecation")
	public static String guardarImagenTemporal(MultipartFile archivoSubir,HttpServletRequest request) throws IOException,Exception{
		String fileName="";
		String ruta="";
		MultipartFile file=archivoSubir;
		InputStream inputStream=null;
		boolean val=false;
		OutputStream outputStream=null;
		if(file.getSize() > 0){
			inputStream=file.getInputStream();
			ruta=Constantes.ROOT_ROSOURCES + Constantes.ROOT_TEMP+ Constantes.ROOT_SLASH + file.getOriginalFilename();
			String ext=ruta.substring(ruta.lastIndexOf(".") + 1,ruta.length()).trim().toLowerCase();

			System.out.println("formato:" + ext);

			if((ext.equals(Constantes.JPEG))){
				val=true;
			}
			else if((ext.equals(Constantes.JPG))){
				val=true;
			}
			else if((ext.equals(Constantes.PNG))){
				val=true;
			}
			else if((ext.equals(Constantes.GIF))){
				val=true;
			}

			if(!val){
				return "0";
			}

			if(file.getSize() > 100000000){
				System.out.println("2MB" + file.getSize());
				return "1";
			}

			fileName=request.getRealPath("") + ruta;
			outputStream=new FileOutputStream(fileName);
			int readBytes=0;
			byte[] buffer=new byte[10000];
			while((readBytes=inputStream.read(buffer,0,10000)) != -1){
				outputStream.write(buffer,0,readBytes);
			}
			outputStream.close();
			inputStream.close();
		}
		return ruta;
	}

	private static BufferedImage resizeImage(BufferedImage originalImage,int type,int width,int height){
		System.out.println("type:"+type);
		BufferedImage resizedImage=new BufferedImage(width,height,type);
		Graphics2D g=resizedImage.createGraphics();
		g.drawImage(originalImage,0,0,width,height,null);
		g.dispose();
		return resizedImage;
	}

	@SuppressWarnings("deprecation")
	public static int guardarImagen(int x,int y,int w,int h,String fileRuta,String nameImage,String nuevaRuta,String formato,int width,int height,HttpServletRequest request) throws IOException{
		try{
			log.info("request.getRealPath():"+request.getRealPath(""));
			log.info("fileRuta:"+fileRuta);
			String fileName=request.getRealPath("") + fileRuta;
			log.info("fileName:"+fileName);
			log.info("nuevaRuta:"+nuevaRuta);
			log.info("nameImage:"+nameImage);
			String ruta=request.getRealPath("") + nuevaRuta + Constantes.ROOT_SLASH + nameImage;
			log.info("ruta"+ruta);
			log.info("ImageIO.read(new File(fileName)):"+fileName);
			BufferedImage image=ImageIO.read(new File(fileName));
			System.out.println("image.getType():"+image.getType());
			image=resizeImage(image,5,width,height);
			ImageIO.write(image,formato,new File(ruta));
			BufferedImage bi=image.getSubimage(x,y,w,h);
			ImageIO.write(bi,formato,new File(ruta));
			return 1;
		}
		catch(Exception e){
			System.out.println(e);
			e.printStackTrace();
			return 0;
		}
	}
	
	public static int getWithImagen(String fileName){
		int with=0;
		try{
			BufferedImage image=ImageIO.read(new File(fileName));
			with=image.getWidth();
		}
		catch(IOException e){
			e.printStackTrace();
		}
		return with;
	}
	
	public static int getHeightImagen(String fileName){
		int height=0;
		try{
			BufferedImage image=ImageIO.read(new File(fileName));
			height=image.getHeight();
		}
		catch(IOException e){
			e.printStackTrace();
		}
		return height;
	}
	
	
	/*
	 * public static void main(String[] args){
	 * 
	 * String cod=generarCodigo(Producto.class.getSimpleName(),"nME");
	 * System.out.println("cod:" + cod); try{ File f=new File(
	 * "D:\\CIBERTEC\\6to\\PI\\pruebasSTS\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\Deliccio\\resources\\images\\"
	 * + cod + ".txt"); System.out.println("f:" + f.isDirectory());
	 * System.out.println("f:" + f.getAbsolutePath()); if(!f.exists()){
	 * f.createNewFile(); } } catch(Exception e){ System.out.println("e:" + e);
	 * }
	 * 
	 * }
	 */

}
